﻿//-----------------------------------------------------------------------
// <copyright file="AutomapperTypeAdapterFactory.cs" company="ET">
//     Copyright Mulala. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Mulala.Cavan.Infrastructure.CrossCutting.NetFramework
{
    using System;
    using System.Linq;
    using AutoMapper;
    using Mulala.Cavan.Infrastructure.CrossCutting;

    /// <summary>
    /// automapper type adapter factory
    /// </summary>
    public class AutomapperTypeAdapterFactory : ITypeAdapterFactory
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="AutomapperTypeAdapterFactory"/> class.
        /// </summary>
        public AutomapperTypeAdapterFactory()
        {
            ////scan all assemblies finding Automapper Profile
            var profiles = AppDomain.CurrentDomain
                                    .GetAssemblies()
                                    .SelectMany(a => a.GetTypes())
                                    .Where(t => t.BaseType == typeof(Profile));

            Mapper.Initialize(cfg =>
            {
                foreach (var item in profiles)
                {
                    if (item.FullName != "AutoMapper.SelfProfiler`2")
                    {
                        cfg.AddProfile(Activator.CreateInstance(item) as Profile);
                    }
                } 
            });
        }

        #endregion

        #region ITypeAdapterFactory Members

        /// <summary>
        /// Create a type adater
        /// </summary>
        /// <returns>The created ITypeAdapter</returns>
        public ITypeAdapter Create()
        {
            return new AutomapperTypeAdapter();
        }

        #endregion
    }
}
